home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3571 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Type conversion
  5. Date: Tue, 30 Jan 1996 01:14:31 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9601300014.AA22125@dxmint.cern.ch>
  8. References: <4ejjka$2rf@news3.cts.com>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. jfitz@vmbb.cts.com (Jim Fitzgerald) writes:
  14.  
  15. >  Was wondering if a guru out there could tell me why the following
  16.  
  17. There is no need to be a guru to answer the question.  Only basic C
  18. understanding is needed.
  19.  
  20. >code fragment for extracting an long from a buffer does not work.
  21. >Following the bad code, is a fragment that does work.. but is fairly
  22. >cheezy! )..
  23. >
  24. >This code compiles and runs but returns INCORRECT results:
  25. >
  26. >char buffer[512];
  27. >long  node_left, node_right;
  28. >{
  29. >  node_left  =  (long)*(buffer+4);
  30. >  node_right=  (long)*(buffer+8);
  31. >}
  32.  
  33. What you say here is: "take the char stored at address buffer+4 and
  34. convert it to long".  This is clearly not what you meant, so the correct
  35. expression is: 
  36.  
  37.     node_left = *(long *)(buffer+4);
  38.  
  39. which converts buffer+4 into a pointer to long and then retrieves the
  40. long value stored at that address (dereferences the pointer in C-speak).
  41.  
  42. Note that this kind of code is very unsafe, because there is no guarantee
  43. that buffer+4 is a legal address for a long.  If it isn't, the program will
  44. crash and burn on platforms which are sensitive to data alignment issues.
  45.  
  46. Dan
  47. -- 
  48. Dan Pop
  49. CERN, CN Division
  50. Email: danpop@mail.cern.ch 
  51. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  52.